const Base = require('./base.js');
const moment = require('moment');
const taskConfig = {
    graphic: 41,//41图文分享、42活动参与、43活动分享、44问卷参与、45问卷分享、46门店活动
    active1: 42,
    active2: 43,
    question1: 44,
    question2: 45,
    siteactive: 46,
    register:21,
    share:46//体验分享
};
module.exports = class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'id';
        const shelves_beg = this.get('begin') || '';
        const shelves_end = this.get('end') || '';
        const taskname = this.get('taskname') || '';
        const state = this.get('state') || '';
        const custom = this.get('custom') || '';
        let seachdata = { id: ['>', 0] }, timesearch = {};
        if (state || state === 0) {
            seachdata.is_delete = state;
        }
        if (custom || custom === 0) {
            seachdata.custom = custom;
        }
        if (taskname) {
            seachdata.content = ['like', `%${taskname}%`];
        }

        if (shelves_beg || shelves_end) {
            if (shelves_beg) {
                timesearch['egt'] = shelves_beg;
            }
            if (shelves_end) {
                timesearch['elt'] = shelves_end;
            }
            seachdata.update_time = timesearch;
        }

        const model = this.model('task');
        const data = await model.where(
            seachdata
        ).order([sortField]).page(page, size).countSelect();
        return this.success(data);
    }

    async saveAction() {
        const model = this.model('task');
        const values = this.post();
        let id = this.post('id');
        const goods_id = this.post('goods_id');
        values['user_id'] = think.userId;
        if(!values.pic){
            values.pic=this.gotTaskPic(values.source_type);
        }
        const task = await model.where({custom:1,source_type:values.source_type,source_id:values.source_id}).find();
        if(!think.isEmpty(task)){
            return this.fail(400,'该自定义任务已存在，可以重新激活修改');
        }
        if (goods_id) {
            let data = await model.where({ goods_id: goods_id }).find();
            if (!think.isEmpty(data)) {
                await model.where({ goods_id: goods_id }).update(values);
            } else {
                values['id'] = 0;
                id = await model.add(values);
                values['id'] = id;
            }

        } else {
            if(values['source_type'] in [41,43,45]){
                values['content'] = '分享：'+values['content'];
            }else if(values['source_type'] in [42,44,46]){
                values['content'] = '参与：'+values['content'];
            }

            values['id'] = 0;
            id > 0 ? id = await model.where({ id: id }).update(values) : id = await model.add(values);
            values['id'] = id;
        }
        return this.success(values);
    }
    async updateAction() {
        const model = this.model('task');
        const values = this.post();
        const id = this.post('id');
        values['user_id'] = think.userId;
        if(!values.pic){
            values.pic=this.gotTaskPic(values.source_type);
        }
        let data = await model.where({ id: id }).update(values);
        return this.success(data);
    }

    async readAction() {
        const model = this.model('task');
        const id = this.get('id');
        const data = await model.where({ id: id }).find();
        return this.success(data);
    }
    /**
    * 任务激活
    */
    async activeAction() {
        const model = this.model('task');
        const values = this.post();
        const id = this.post('id');
        values['is_delete'] = 0;
        values['user_id'] = think.userId;
        let data = await model.where({ id: id }).update(values);
        return this.success(data);
    }
    /**
     * 任务冻结
     */
    async freezeAction() {
        const model = this.model('task');
        const id = this.post('id');
        let data = await model.where({ id: id }).update({ is_delete: 1 });
        return this.success(data);
    }

    /**
    * 获取已激活任务
    */
    async getActiveTaskAction() {
        const model = this.model('task');
        let seachdata = { id: ['>', 0] };
        const state = this.get('state') || '';
        const custom = this.get('custom') || '';
        if (state || state === 0) {
            seachdata.is_delete = state;
        }
        if (custom || custom === 0) {
            seachdata.custom = custom;
        }
        let data = await model.where(seachdata).select();
        return this.success(data);
    }

    async deleteAction() {
        const model = this.model('task');
        const id = this.post('id');
        let data = await model.where({ id: id }).delete();
        return this.success(data);
    }

    async selectTasksAction() {
        const model2 = this.model('active');
        const model1 = this.model('graphic');
        const model3 = this.model('question');
        const values = this.post();
        let data;
        switch (values.sourceType) {
            case taskConfig.graphic:
                data = await model1.field("id,title").select();
                break;
            case taskConfig.active1:
                data = await model2.field("id,title").select();
                break;
            case taskConfig.active2:
                data = await model2.field("id,title").select();
                break;
            case taskConfig.question1:
                data = await model3.field("id,name as title").select();
                break;
            case taskConfig.question2:
                data = await model3.field("id,name as title").select();
                break;
            case taskConfig.siteactive:
                data = await this.model('active_site').field("id,name as title").select();
                break;
            default:
                data = await model1.field("id,title").select();
        }
        return this.success(data);
    }

    /**
     * 奖励查询
     */
    async rewardSearchAction() {
        const model = this.model('task_integral');
        const values = this.get();
        let searchData={ 'hiolabs_task_integral.task_id': ['>', 0],'hu.nickname': ['!=', null]},timesearch = {};
        // let sql = 'hiolabs_task_integral.task_id>0 and hu.nickname is not null ';
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const shelves_beg = this.get('begin') || '';
        const shelves_end = this.get('end') || '';
        const mobile = this.get('mobile') || '';
        const task_id = this.get('task_id') || '';

        if (mobile) {
            searchData['hu.mobile'] = ['like', `%${mobile}%`];
            // sql+= ' and hu.mobile like \'%'+mobile +'%\'';
        }
        if (task_id) {
            searchData['task_id'] = task_id;
            // sql+= ' and hiolabs_task_integral.task_id='+task_id;
        }

        if (shelves_beg || shelves_end) {
            if (shelves_beg) {
                timesearch['egt'] = shelves_beg;
                // sql+= ' and hiolabs_task_integral.create_time>='+shelves_beg;
            }
            if (shelves_end) {
                // timesearch['elt'] = shelves_end;
                timesearch['lt'] = moment(shelves_end).add(1, "day").format("YYYY-MM-DD");
                // sql+= ' and hiolabs_task_integral.create_time<='+shelves_end;
            }
            searchData['hiolabs_task_integral.create_time'] = timesearch;
        }

        let data = await model.join({ table: 'task',  join: 'left',as:'tk',on: ['task_id', 'id'] })
        .join({ table: 'user',  join: 'left',as:'hu', on: ['user_id', 'id'] })
        .where(searchData).order('hiolabs_task_integral.id').field("hiolabs_task_integral.*,tk.content,hu.id as uid,hu.nickname,hu.mobile").page(page,size).countSelect();
        for (const item of data.data) {
            item.nickname = Buffer.from(item.nickname, 'base64').toString();
        }
        data.rewardTotal = await model.where(searchData)
        .join({ table: 'task',  join: 'left',as:'tk',on: ['task_id', 'id'] })
        .join({ table: 'user',  join: 'left',as:'hu', on: ['user_id', 'id'] }).sum('hiolabs_task_integral.integral');
        data.rewardTimes = await model.where(searchData).join({ table: 'task',  join: 'left',as:'tk',on: ['task_id', 'id'] })
        .join({ table: 'user',  join: 'left',as:'hu', on: ['user_id', 'id'] })
        .count('hiolabs_task_integral.id');
        data.rewardUsers = await model.where(searchData).join({ table: 'task',  join: 'left',as:'tk',on: ['task_id', 'id'] })
        .join({ table: 'user',  join: 'left',as:'hu', on: ['user_id', 'id'] })
        .count('distinct hiolabs_task_integral.user_id');

        if(!data.rewardTotal) data.rewardTotal=0;
        return this.success(data);
    }

    /**
     * 奖励排行
     */
    async rewardStaticAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 20;
        const mobile = this.get('mobile') || '';
        const nickname = this.get('nickname') || '';
        let searchdata={ 'ti.task_id': ['>', 0]};

        if (mobile) {
            searchdata['hiolabs_user.mobile'] = ['like', `%${mobile}%`];
        }
        if (nickname) {
            searchdata['hiolabs_user.nickname'] = ['like', `%${nickname}%`];
        }
        const model = this.model('user');
        const integral_model = this.model('task_integral');
        // const data = await model.where({ integral: ['>', 0] }).order('integral desc').field('id as uid,nickname,mobile,integral').page(page,size).countSelect();
        const total = await model.where(searchdata).join({ table: 'task_integral',  join: 'right',as:'ti',on: ['id', 'user_id'] })
        .count('distinct ti.user_id');
        const data = await model.where(searchdata).join({ table: 'task_integral',  join: 'right',as:'ti',on: ['id', 'user_id'] })
        .field('ti.user_id as uid,sum(ti.integral) as total_reward').group('ti.user_id')
        .order('total_reward desc').page(page,size).countSelect(total);
        for(const item of data.data){ 
            let user = await model.where({id:item.uid}).find();
            item.nickname = user.nickname?Buffer.from(user.nickname, 'base64').toString():'已删除';
            item.mobile = user.mobile;
            item.integral = user.integral;

            item.activeInter=await integral_model.where({task_type: ["IN", [taskConfig.active1, taskConfig.active2,taskConfig.siteactive]],user_id:item.uid}).sum('integral');
            item.questionInter=await integral_model.where({task_type: ["IN", [taskConfig.question1, taskConfig.question2]],user_id:item.uid}).sum('integral');
            item.graphicInter=await integral_model.where({task_type: taskConfig.graphic,user_id:item.uid}).sum('integral');
            item.shareInter=await integral_model.where({task_type: taskConfig.share,user_id:item.uid}).sum('integral');
            item.registerInter=await integral_model.where({task_type: taskConfig.register,user_id:item.uid}).sum('integral');
            item.systemInter=await integral_model.where({task_type: ["between", 1,20],user_id:item.uid}).sum('integral');//系统任务
            item.activeInter=item.activeInter?item.activeInter:0;
            item.questionInter=item.questionInter?item.questionInter:0;
            item.graphicInter=item.graphicInter?item.graphicInter:0;
            item.shareInter=item.shareInter?item.shareInter:0;
            item.registerInter=item.registerInter?item.registerInter:0;
            item.systemInter=item.systemInter?item.systemInter:0;
        }
        return this.success(data);
    }


    /**
     * 奖励统计
     */
    async rewardTotalAction() {
        const page = this.post('page') || 1;
        const size = this.post('size') || 10;
        const begin = this.post('begin') || moment().subtract(30, "day").format("YYYY-MM-DD");
        const nend = this.post('end') || moment().format('YYYY-MM-DD');
        const end = moment(nend).add(1, "day").format("YYYY-MM-DD");
        const task_ids =this.post('task_ids') || [];
        const type =this.post('type') || 3;//1日，2周，3月
        let timesearch={};

        if (begin || end) {
            if (begin) {
                timesearch['egt'] = begin;
            }
            if (end) {
                timesearch['lt'] = end;
            }
        }

        const integral_model = this.model('task_integral');
        const totalsum = await integral_model.where({task_id:['>',0],create_time:timesearch}).sum('integral');
        const usersum = await integral_model.where({task_id:['>',0],create_time:timesearch}).count('distinct user_id');
        const totalnumber = await integral_model.where({task_id:['>',0],create_time:timesearch}).count('id');
        const tasksum = await integral_model.where({task_id:['>',0],create_time:timesearch}).count('distinct task_id'); 

        let sumdata,numberdata,returnsum=[],returnnumber=[];
        if (task_ids&&task_ids.length>0) {
            for(const item of task_ids){
                let taskdata= await this.model('task').where({id:item}).find();
                switch (type) {
                    case 1:
                        sumdata = await integral_model.where({task_id:item,create_time:timesearch})
                        .field('DATE_FORMAT(create_time,\'%Y-%m-%d\') as time,sum(integral) as integral').group('time').select();
                        numberdata = await integral_model.where({task_id:item,create_time:timesearch})
                        .field('DATE_FORMAT(create_time,\'%Y-%m-%d\') as time,count(id) as num').group('time').select();
                        break;
                    case 2:
                        sumdata = await integral_model.where({task_id:item,create_time:timesearch})
                        .field('DATE_FORMAT(create_time,\'%Y-%u\') as time,sum(integral) as integral').group('time').select();
                        numberdata = await integral_model.where({task_id:item,create_time:timesearch})
                        .field('DATE_FORMAT(create_time,\'%Y-%u\') as time,count(id) as num').group('time').select();
                        break;
                    case 3:
                        sumdata = await integral_model.where({task_id:item,create_time:timesearch})
                        .field('DATE_FORMAT(create_time,\'%Y-\%m\') as time,sum(integral) as integral').group('time').select();
                        numberdata = await integral_model.where({task_id:item,create_time:timesearch})
                        .field('DATE_FORMAT(create_time,\'%Y-\%m\') as time,count(id) as num').group('time').select();
                        break;
                    default:
                        sumdata = await integral_model.where({task_id:item,create_time:timesearch})
                        .field('DATE_FORMAT(create_time,\'%Y-\%m\') as time,sum(integral) as integral').group('time').select();
                        numberdata = await integral_model.where({task_id:item,create_time:timesearch})
                        .field('DATE_FORMAT(create_time,\'%Y-\%m\') as time,count(id) as num').group('time').select();
                }
                sumdata=this.getValuename(begin,end,type,sumdata);
                numberdata=this.getValuename(begin,end,type,numberdata);
                returnsum.push({name:taskdata.content,data:sumdata});
                returnnumber.push({name:taskdata.content,data:numberdata});
            }
        }else{
            switch (type) {
                case 1:
                    sumdata = await integral_model.where({task_id:['>',0],create_time:timesearch})
                    .field('DATE_FORMAT(create_time,\'%Y-%m-%d\') as time,sum(integral) as integral').group('time').select();
                    numberdata = await integral_model.where({task_id:['>',0],create_time:timesearch})
                    .field('DATE_FORMAT(create_time,\'%Y-%m-%d\') as time,count(id) as num').group('time').select();
                    break;
                case 2:
                    sumdata = await integral_model.where({task_id:['>',0],create_time:timesearch})
                    .field('DATE_FORMAT(create_time,\'%Y-%u\') as time,sum(integral) as integral').group('time').select();
                    numberdata = await integral_model.where({task_id:['>',0],create_time:timesearch})
                    .field('DATE_FORMAT(create_time,\'%Y-%u\') as time,count(id) as num').group('time').select();
                    break;
                case 3:
                    sumdata = await integral_model.where({task_id:['>',0],create_time:timesearch})
                    .field('DATE_FORMAT(create_time,\'%Y-\%m\') as time,sum(integral) as integral').group('time').select();
                    numberdata = await integral_model.where({task_id:['>',0],create_time:timesearch})
                    .field('DATE_FORMAT(create_time,\'%Y-\%m\') as time,count(id) as num').group('time').select();
                    break;
                default:
                    sumdata = await integral_model.where({task_id:['>',0],create_time:timesearch})
                    .field('DATE_FORMAT(create_time,\'%Y-\%m\') as time,sum(integral) as integral').group('time').select();
                    numberdata = await integral_model.where({task_id:['>',0],create_time:timesearch})
                    .field('DATE_FORMAT(create_time,\'%Y-\%m\') as time,count(id) as num').group('time').select();
            }
            sumdata=this.getValuename(begin,end,type,sumdata);
            numberdata=this.getValuename(begin,end,type,numberdata);
            returnsum.push({name:'全部任务',data:sumdata});
            returnnumber.push({name:'全部任务',data:numberdata});

        }
        // console.log(moment('2020-07').format('YYYY.MM.DD'));
        // console.log(moment().day("Monday").year('2020').week('30')>moment('2020-07-19'));
        // console.log(moment().day("sunday").year('2020').week('30'));
        // console.log(moment('2020-07')>moment('2020-06-01'));
        return this.success({
            total:{
                totalsum:totalsum,
                usersum:usersum,
                totalnumber:totalnumber,
                tasksum:tasksum,
                avgreward:(totalnumber/usersum).toFixed(4),
                avgtask:(totalnumber/tasksum).toFixed(4)
            },
            sumdata:returnsum,
            numberdata:returnnumber
        });
    }

    getValuename(begin,end,type,arr){
        if(type===1) return arr;
        
        for(let i=0;i<arr.length;i++){
            let data=arr[i].time,bg,ed,us;
            if(type===3){
                bg=moment(data);
                ed=moment(data).endOf('month');
            }else{
                us=data.split('-');
                bg=moment().day("Sunday").year(us[0]).week(us[1]);
                ed=moment().day("Saturday").year(us[0]).week(us[1]);
            }
            if(i===0) bg=moment(begin)>bg?moment(begin):bg;
            if(i===arr.length-1) ed=moment(end)<ed?moment(end):ed;
            arr[i].time=bg.format('YYYY.MM.DD')+'至'+ed.format('YYYY.MM.DD');
        }
        return arr;
    }
    gotTaskPic(source_type){
        let pic = '';
        switch (source_type) {
            case 1:
                pic='https://www.coastalinfo.cn/coastalShop/static/temp/phone.png';
                return pic;
            case 2:
                pic='';
                return pic;
            case 3:
                pic='';
                return pic;
            case 4:
                pic='https://www.coastalinfo.cn/coastalShop/static/temp/phone.png';
                return pic;
            case 5:
                pic='https://www.coastalinfo.cn/coastalShop/static/temp/write.png';
                return pic;
            case 6:
                pic='https://www.coastalinfo.cn/coastalShop/static/temp/share.png';
                return pic;
            case 7:
                pic='https://www.coastalinfo.cn/coastalShop/static/temp/share.png';
                return pic;
            case 8:
                pic='https://www.coastalinfo.cn/coastalShop/static/temp/share.png';
                return pic;
            case 9:
                pic='https://www.coastalinfo.cn/coastalShop/static/temp/promote.png';
                return pic;
            case taskConfig.graphic:
                pic = 'https://www.coastalinfo.cn/coastalShop/static/temp/share.png';
                return pic;
            case taskConfig.active1:
                pic = '';
                return pic;
            case taskConfig.active2:
                pic = 'https://www.coastalinfo.cn/coastalShop/static/temp/share.png';
                return pic;
            case taskConfig.question1:
                pic = 'https://www.coastalinfo.cn/coastalShop/static/temp/question.png';
                return pic;
            case taskConfig.question2:
                pic = 'https://www.coastalinfo.cn/coastalShop/static/temp/share.png';
                return pic;
            default:
                pic = '';
                return pic;
        }

    }

};